// 主应用类
class MarkEditApp {
    constructor() {
        this.editor = null;
        this.preview = null;
        this.currentFile = null;
        this.isModified = false;
        this.settings = this.loadSettings();
        
        this.init();
    }

    // 初始化应用
    init() {
        this.initializeEditor();
        this.initializePreview();
        this.bindEvents();
        this.updateStatus();
        
        console.log('MarkEdit应用初始化完成');
    }

    // 初始化编辑器
    initializeEditor() {
        const editorElement = document.getElementById('markdown-editor');
        if (typeof CodeMirror !== 'undefined') {
            this.editor = new MarkdownEditor(editorElement);
            this.editor.onChange((content) => {
                this.onContentChange(content);
            });
        } else {
            // 降级到普通textarea
            this.editor = new SimpleEditor(editorElement);
            editorElement.addEventListener('input', (e) => {
                this.onContentChange(e.target.value);
            });
        }
        
        // 触发编辑器初始化完成事件
        setTimeout(() => {
            document.dispatchEvent(new CustomEvent('editorInitialized', {
                detail: { editor: this.editor }
            }));
        }, 100);
    }

    // 初始化预览
    initializePreview() {
        this.preview = new MarkdownPreview(document.getElementById('preview-content'));
    }

    // 绑定事件
    bindEvents() {
        // 文件操作
        document.getElementById('new-file').addEventListener('click', () => this.newFile());
        document.getElementById('open-file').addEventListener('click', () => this.openFile());
        document.getElementById('save-file').addEventListener('click', () => this.saveFile());

        // 视图切换
        document.getElementById('edit-mode').addEventListener('click', () => this.setViewMode('edit'));
        document.getElementById('preview-mode').addEventListener('click', () => this.setViewMode('preview'));
        document.getElementById('split-mode').addEventListener('click', () => this.setViewMode('split'));

        // 导出功能
        document.getElementById('export-pdf').addEventListener('click', () => this.exportFile('pdf'));
        document.getElementById('export-word').addEventListener('click', () => this.exportFile('word'));
        document.getElementById('export-html').addEventListener('click', () => this.exportFile('html'));

        // 设置面板
        document.getElementById('settings').addEventListener('click', () => this.showSettings());
        document.getElementById('close-settings').addEventListener('click', () => this.hideSettings());

        // 编辑器工具
        this.bindEditorTools();

        // 数学符号面板
        this.bindMathSymbols();

        // 键盘快捷键
        this.bindKeyboardShortcuts();

        // 窗口事件
        window.addEventListener('beforeunload', (e) => {
            if (this.isModified) {
                e.preventDefault();
                e.returnValue = '您有未保存的更改，确定要离开吗？';
            }
        });
    }

    // 绑定编辑器工具
    bindEditorTools() {
        const tools = {
            'bold': () => this.insertText('**', '**'),
            'italic': () => this.insertText('*', '*'),
            'heading': () => this.insertText('## ', ''),
            'link': () => this.insertText('[', '](url)'),
            'image': () => this.insertText('![', '](url)'),
            'code': () => this.editor.insertCodeBlock(),
            'table': () => this.editor.insertTable(),
            'inline-math': () => this.editor.insertInlineMath(),
            'block-math': () => this.editor.insertBlockMath()
        };

        Object.keys(tools).forEach(tool => {
            const element = document.getElementById(tool);
            if (element) {
                element.addEventListener('click', tools[tool]);
            }
        });

        // 绑定数学符号按钮
        this.bindMathSymbols();
    }

    // 绑定数学符号事件
    bindMathSymbols() {
        // 绑定数学符号下拉按钮
        const mathSymbolsBtn = document.getElementById('math-symbols');
        if (mathSymbolsBtn) {
            mathSymbolsBtn.addEventListener('click', (e) => {
                e.preventDefault();
                e.stopPropagation();
                const dropdown = mathSymbolsBtn.closest('.math-dropdown');
                if (dropdown) {
                    dropdown.classList.toggle('active');
                }
            });
        }
        
        // 绑定符号按钮
        document.addEventListener('click', (e) => {
            if (e.target.classList.contains('symbol-btn')) {
                e.preventDefault();
                
                const symbol = e.target.getAttribute('data-symbol');
                const template = e.target.getAttribute('data-template');
                
                if (symbol) {
                    this.editor.insertMathSymbol(symbol);
                } else if (template) {
                    this.editor.insertMathTemplate(template);
                }
                
                // 关闭下拉菜单
                const dropdown = e.target.closest('.math-dropdown');
                if (dropdown) {
                    dropdown.classList.remove('active');
                }
            }
        });
        
        // 点击其他地方关闭下拉菜单
        document.addEventListener('click', (e) => {
            if (!e.target.closest('.math-dropdown')) {
                const activeDropdowns = document.querySelectorAll('.math-dropdown.active');
                activeDropdowns.forEach(dropdown => {
                    dropdown.classList.remove('active');
                });
            }
        });
    }

    // 绑定键盘快捷键
    bindKeyboardShortcuts() {
        document.addEventListener('keydown', (e) => {
            if (e.ctrlKey || e.metaKey) {
                switch (e.key) {
                    case 'n':
                        e.preventDefault();
                        this.newFile();
                        break;
                    case 'o':
                        e.preventDefault();
                        this.openFile();
                        break;
                    case 's':
                        e.preventDefault();
                        this.saveFile();
                        break;
                    case 'b':
                        e.preventDefault();
                        this.insertText('**', '**');
                        break;
                    case 'i':
                        e.preventDefault();
                        this.insertText('*', '*');
                        break;
                    case 'm':
                        e.preventDefault();
                        if (e.shiftKey) {
                            // Ctrl+Shift+M: 块级数学公式
                            this.editor.insertBlockMath();
                        } else {
                            // Ctrl+M: 行内数学公式
                            this.editor.insertInlineMath();
                        }
                        break;
                }
            }
        });
    }

    // 内容变化处理
    onContentChange(content) {
        this.isModified = true;
        this.updateStatus();
        this.preview.update(content);
        this.updateWordCount(content);
    }

    // 插入文本
    insertText(before, after) {
        if (this.editor && this.editor.insertText) {
            this.editor.insertText(before, after);
        }
    }

    // 插入表格
    insertTable() {
        const table = `| 列1 | 列2 | 列3 |
|-----|-----|-----|
| 内容1 | 内容2 | 内容3 |
| 内容4 | 内容5 | 内容6 |`;
        this.insertText(table, '');
    }

    // 新建文件
    newFile() {
        if (this.isModified && !confirm('当前文档有未保存的更改，确定要新建文档吗？')) {
            return;
        }
        
        this.editor.setValue('');
        this.currentFile = null;
        this.isModified = false;
        this.updateStatus();
    }

    // 打开文件
    openFile() {
        const input = document.createElement('input');
        input.type = 'file';
        input.accept = '.md,.markdown,.txt';
        input.onchange = (e) => {
            const file = e.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = (e) => {
                    this.editor.setValue(e.target.result);
                    this.currentFile = file.name;
                    this.isModified = false;
                    this.updateStatus();
                };
                reader.readAsText(file);
            }
        };
        input.click();
    }

    // 保存文件
    saveFile() {
        const content = this.editor.getValue();
        const blob = new Blob([content], { type: 'text/markdown' });
        const url = URL.createObjectURL(blob);
        
        const a = document.createElement('a');
        a.href = url;
        a.download = this.currentFile || 'document.md';
        a.click();
        
        URL.revokeObjectURL(url);
        this.isModified = false;
        this.updateStatus();
    }

    // 导出文件
    async exportFile(format) {
        const content = this.editor.getValue();
        if (!content.trim()) {
            alert('请先输入内容再导出');
            return;
        }

        // 使用前端导出管理器
        if (window.exportManager) {
            switch (format) {
                case 'pdf':
                    window.exportManager.exportToPDF();
                    break;
                case 'word':
                    window.exportManager.exportToWord();
                    break;
                case 'html':
                    window.exportManager.exportToHTML();
                    break;
                default:
                    alert('不支持的导出格式');
            }
        } else {
            alert('导出功能正在加载中，请稍后重试');
        }
    }

    // 设置视图模式
    setViewMode(mode) {
        const editorPanel = document.getElementById('editor-panel');
        const previewPanel = document.getElementById('preview-panel');
        const buttons = document.querySelectorAll('.btn-toggle');

        // 移除所有active类
        buttons.forEach(btn => btn.classList.remove('active'));

        switch (mode) {
            case 'edit':
                editorPanel.style.display = 'flex';
                previewPanel.style.display = 'none';
                document.getElementById('edit-mode').classList.add('active');
                break;
            case 'preview':
                editorPanel.style.display = 'none';
                previewPanel.style.display = 'flex';
                document.getElementById('preview-mode').classList.add('active');
                break;
            case 'split':
                editorPanel.style.display = 'flex';
                previewPanel.style.display = 'flex';
                document.getElementById('split-mode').classList.add('active');
                break;
        }
    }

    // 显示设置面板
    showSettings() {
        document.getElementById('settings-panel').classList.remove('hidden');
        this.loadSettingsToUI();
    }

    // 隐藏设置面板
    hideSettings() {
        document.getElementById('settings-panel').classList.add('hidden');
        this.saveSettingsFromUI();
    }

    // 加载设置
    loadSettings() {
        const defaultSettings = {
            imageDpi: '300',
            imageFormat: 'png',
            enableMermaid: true,
            enablePlantuml: true,
            enableKatex: true,
            enableVim: false,
            enableWordWrap: true,
            enableLineNumbers: true,
            plantumlServer: 'http://localhost:8081',
            plantumlOfflineMode: false
        };

        try {
            const saved = localStorage.getItem('markedit-settings');
            return saved ? { ...defaultSettings, ...JSON.parse(saved) } : defaultSettings;
        } catch {
            return defaultSettings;
        }
    }

    // 保存设置
    saveSettings() {
        localStorage.setItem('markedit-settings', JSON.stringify(this.settings));
    }

    // 从UI加载设置
    loadSettingsToUI() {
        document.getElementById('image-dpi').value = this.settings.imageDpi;
        document.getElementById('image-format').value = this.settings.imageFormat;
        document.getElementById('enable-mermaid').checked = this.settings.enableMermaid;
        document.getElementById('enable-plantuml').checked = this.settings.enablePlantuml;
        document.getElementById('enable-katex').checked = this.settings.enableKatex;
        document.getElementById('enable-vim').checked = this.settings.enableVim;
        document.getElementById('enable-word-wrap').checked = this.settings.enableWordWrap;
        document.getElementById('enable-line-numbers').checked = this.settings.enableLineNumbers;
        document.getElementById('plantuml-server').value = this.settings.plantumlServer;
        document.getElementById('plantuml-offline-mode').checked = this.settings.plantumlOfflineMode;
    }

    // 从UI保存设置
    saveSettingsFromUI() {
        this.settings.imageDpi = document.getElementById('image-dpi').value;
        this.settings.imageFormat = document.getElementById('image-format').value;
        this.settings.enableMermaid = document.getElementById('enable-mermaid').checked;
        this.settings.enablePlantuml = document.getElementById('enable-plantuml').checked;
        this.settings.enableKatex = document.getElementById('enable-katex').checked;
        this.settings.enableVim = document.getElementById('enable-vim').checked;
        this.settings.enableWordWrap = document.getElementById('enable-word-wrap').checked;
        this.settings.enableLineNumbers = document.getElementById('enable-line-numbers').checked;
        this.settings.plantumlServer = document.getElementById('plantuml-server').value;
        this.settings.plantumlOfflineMode = document.getElementById('plantuml-offline-mode').checked;
        
        this.saveSettings();
    }

    // 更新状态栏
    updateStatus() {
        const fileStatus = document.getElementById('file-status');
        const connectionStatus = document.getElementById('connection-status');
        
        fileStatus.textContent = this.isModified ? '未保存' : '已保存';
        connectionStatus.textContent = '已连接';
    }

    // 更新字数统计
    updateWordCount(content) {
        const wordCount = content.length;
        document.getElementById('word-count').textContent = `字数: ${wordCount}`;
    }
}

// 应用启动
document.addEventListener('DOMContentLoaded', () => {
    window.markEditApp = new MarkEditApp();
});